package com.qianli.cashmama.trade.openApi.utils.shumei;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.TimeUtils;
import com.qianli.cashmama.trade.openApi.utils.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by ykpbean kangping.ying@yuntu-inc.com
 *
 * @description
 * @create 2018-01-23 上午10:22
 */

public class ShuMeiHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(ShuMeiHandler.class);


    public static List<String> loanAppList = Arrays.asList("Loan On AadharCard", "Umoja loans", "BaaziNow", "Zulu Loans", "Oloan", "Upesa",
            "Way2money", "Aadhar Loan", "Cashiya", "Halisi Loans", "SlicePay", "Finacri", "MoNeed", "Capital Float", "SBI Loans", "HalaPlay",
            "LoanIt", "Pata cash", "KrazyBee", "ABD Loan", "Rupeek", "InstaCash", "Cashify", "CashNow", "Kissht", "Salary Now", "QuickCredit",
            "MoneyView", "Apnapaisa", "PhoneParLoan", "RupeeLend", "RupeeLend", "InstantLoan", "MoneyTap", "PaySense", "Avail",
            "IndPay", "GoRupee", "ePayLater", "InstaLoan", "Udhaar Card", "Money in Minutes", "DealsOfLoan", "TachyLoans", "MoneyLoji",
            "EarlySalary", "CASHe", "Loans", "CashUp", "KreditBee", "LoanAdda", "m-Pesa", "IIFL Loans", "FlashCash", "10MinuteLoan", "FlexSalary",
            "ATL", "ZestMoney App", "Rapid Rupee", "LazyPay", "MONEYKIT", "Personal Loan", "Localoan", "Advance Salary", "AbhiPaisa", "Lendingkart",
            "LenDenClub", "Bajaj Finserv", "Indiabulls Dhani", "InstaMoney", "Salary Dost", "BetRally", "Capital First", "Cashkumar", "Faircent",
            "Yaarii", "SmartCoin", "WifiCash", "mParivahan", "InCred", "Cash+", "LoanAssist", "Loantap", "CashBean", "AB TEJ", "Credy", "MoneyOnApp - PF",
            "ZestMoney", "LoanFront", "iMuthoot", "Loanbaba", "Loan Dost", "Loan Globally", "Quick Loan Credit", "ZestMoney Unofficial", "Muthoot Blue",
            "Bulb Smash Cash", "Udhaar", "Rupee Redee", "5Paisa", "Finance Buddha", "Creditt", "Epaylater-Merchant", "Azima Loans", "Kuber StarLine",
            "OkCredit", "EMI + Financial", "UltraCash", "Snapay", "Instant Loans", "Robocash", "ObcmPAY", "OXYLOANS", "RupeeCircle", "MudraKwik",
            "Paisabazaar", "StashFin", "aytm Money", "Home Credit India", " Cash Jet", "IDFC FIRST Loans", " Atome Credit", "Future Pay", "SmartLoan",
            "FCL", "Aadhar Card Pe Loan", "SBFC", "Branch", "CreditMantri", "Indiabulls Homeloans", "Comfy Loan", "CashSuvidha", "TVS Credit Saathi",
            "OGL", "Chota Mota", "ETMONEY", "Shubh Loans", "Smart Money", " Memory saver", "ABD Loan", "Indiabulls Partner", "FastDhan", "Money Club",
            "Kwik Cash", "MoneyOnMobile", "JioMoney", "MudraKwik", "Paisabazaar", "StashFin", "aytm Money", "Home Credit India", "Cash Jet", "IDFC FIRST Loans",
            "Atome Credit", "Future Pay", "SmartLoan", "FCL", "Aadhar Card Pe Loan", "SBFC", "Branch", "CreditMantri", "Indiabulls Homeloans", "Comfy Loan",
            "CashSuvidha", "TVS Credit Saathi", "OGL", "Chota Mota", "ETMONEY", "Shubh Loans", "Smart Money", "Memory saver", "ABD Loan", "Indiabulls Partner",
            "FastDhan", "Money Club", "Kwik Cash", "MoneyOnMobile", "JioMoney", "PayMeIndia", "iGo Insta Personal Loan", "mPokket", " MF-cash", "ayPal",
            "Super Money", "Zestery", "Loan Finder-Pro", "LoanRaahi");


    public static List<String> gambleAppList = Arrays.asList("Poker Raj", "888.com", "Bazzi Games", "theonlypoker", "Khelo365", "ace2three", "RVOnlineGaming: poker Magnet",
            "Rummycircle.com", "Adda52rummy.com", "Bunga365.com", "Poker Stellar", "Poker SD", "Poker-Nation", "Poker Lion.com", "Pokerhigh", "PokerDangal",
            "pokerBazzi.com", "Playtech poker", "Atlantis poker", "pokersaint", "calling station poker", "Mega Hit Poker", "Poker world", "vedio poker free",
            "Poker ", "insta poker", "poker", "vocabpoker", "Legendary video poker", "poker king", "Total Poker", "Scrum Poker Cards", "PPPoker", "Casino Video Poker",
            "TeenPatii KhelGuru", "Pokerist", "Solitaire", "Teen Patti poker offline", "TeenPatti Real", "Poker King", "Poker King vip", "DH TexasPoker",
            "Tempo Poker", "Cocos2D", "Poker Bankroll Tracker", "Adda52 Rummy Lite", "Poker Games", "Float The Turn Poker", "Poker Night", "PokerStars", "Teenpatti indian poker");


    public static void main(String[] args) {
        ShuMeiVo shuMeiVo = getShuMeiVo("http://dc-oss2.oss-ap-south-1.aliyuncs.com/moveFingerprintData/fingerprintData_232376209810391608_1636459293632.json");
        System.err.println(1);
    }

    public static ShuMeiVo getShuMeiVo(String fingerprintInfoUrl) {
        if (StringUtils.isEmpty(fingerprintInfoUrl)) {
            LOGGER.error("== 数美url为空 ==");
            return new ShuMeiVo();
        }

        ShuMeiVo vo = null;
        try {
            String content = HttpUtil.getPage(fingerprintInfoUrl);
            vo = getShuMei(content);
            getAppInfoList(vo);
            getAppNum(vo);
        } catch (Exception e) {
            LOGGER.error("数美数据转化错误2, e", e);
            return new ShuMeiVo();
        }

        return vo;
    }

    /**
     * 获取数美数据
     *
     * @param content
     * @return
     */
    private static ShuMeiVo getShuMei(String content) {
        ShuMeiVo shuMeiVo = null;
        try {
            shuMeiVo = JSONObject.parseObject(content, ShuMeiVo.class);
        } catch (Exception e) {
            LOGGER.error("数美数据转化错误, e", e);
        }
        return shuMeiVo;
    }

    //firstInstallTime + "," + packageName + "," + appName + "," +
    //        (isSystemPackage(packageInfo) ? 0 : 1) + "," +
    //        versionCode + "," +
    //        versionName + "," +
    //        lastUpdateTime)
    private static void getAppInfoList(ShuMeiVo shuMeiVo) {
        int size = 0;
        if (!CollectionUtils.isEmpty(shuMeiVo.getApps())) {
            size = shuMeiVo.getApps().size();
        }

        int size2 = 0;
        if (CollectionUtils.isNotEmpty(shuMeiVo.getAppsList())) {
            size2 = shuMeiVo.getAppsList().size();
        }

        List<String> appsList = shuMeiVo.getApps();
        if (size2 > size) {
            appsList = shuMeiVo.getAppsList();
        }


        List<AppInfo> appInfoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(appsList)) {
            for (String appInfo : appsList) {
                String[] apps = appInfo.split(",");
                AppInfo appInfo1 = new AppInfo();
                appInfo1.setFirstInstallTime(DateUtil.getDates(apps[0], "yyyy-MM-dd HH:mm:ss"));
                appInfo1.setAppPackageName(apps[1]);
                appInfo1.setAppName(apps[2]);
                appInfo1.setIsSysApp(apps[3]);
                appInfo1.setVersionCode(apps[4]);
                appInfo1.setAppVersion(apps[5]);
                appInfo1.setLastUpdateTime(DateUtil.getDates(apps[6], "yyyy-MM-dd HH:mm:ss"));
                appInfoList.add(appInfo1);
            }
        }
        shuMeiVo.setAppInfos(appInfoList);
    }

    private static void getAppNum(ShuMeiVo shuMeiVo) {
        try {
            int countSystem = 0;
            int countNonSystem = 0;
            int countCredit = 0;
            int last7daysAppNum = 0;
            int last15daysAppNum = 0;
            int last30daysAppNum = 0;
            int last60daysAppNum = 0;
            int last7daysCreditAppNum = 0;
            int last15daysCreditAppNum = 0;
            int last30daysCreditAppNum = 0;
            int last60daysCreditAppNum = 0;

            int last7DayGambleAppNum = 0;
            int last15DayGambleAppNum = 0;
            int last30DayGambleAppNum = 0;
            int last60DayGambleAppNum = 0;

            List<String> riskApps = new ArrayList<>();
            List<AppInfo> riskAppInfoList = new ArrayList<>();

            for (AppInfo appInfo : shuMeiVo.getAppInfos()) {
                int days = com.fqgj.common.utils.DateUtil.countDays(new Date(), DateUtil.getDate(appInfo.getFirstInstallTime(), "yyyy-MM-dd HH:mm:ss"));
                //系统应用
                if (appInfo.getIsSysApp().equals("0")) {
                    countSystem = countSystem + 1;
                    //非系统应用
                } else if (appInfo.getIsSysApp().equals("1")) {
                    //非系统应用总数
                    countNonSystem = countNonSystem + 1;
                    //安装时间在60天内的应用
                    if (0 < days && days <= 60) {
                        last60daysAppNum = last60daysAppNum + 1;
                    }
                    if (days > 0 && days <= 30) {
                        last30daysAppNum = last30daysAppNum + 1;
                    }
                    if (days > 0 && days <= 15) {
                        last15daysAppNum = last15daysAppNum + 1;
                    }
                    if (days > 0 && days <= 7) {
                        last7daysAppNum = last7daysAppNum + 1;
                    }
                    //非系统信贷类APP
                    if (loanAppList.contains(appInfo.getAppName())) {
                        //总数
                        countCredit = countCredit + 1;

                        if (0 < days && days <= 60) {
                            last60daysCreditAppNum = last60daysCreditAppNum + 1;
                        }
                        if (days > 0 && days <= 30) {
                            last30daysCreditAppNum = last30daysCreditAppNum + 1;
                        }
                        if (days > 0 && days <= 15) {
                            last15daysCreditAppNum = last15daysCreditAppNum + 1;
                        }
                        if (days > 0 && days <= 7) {
                            last7daysCreditAppNum = last7daysCreditAppNum + 1;
                        }

                        riskApps.add(appInfo.getAppName());
                        riskAppInfoList.add(appInfo);
                    }

                    //非系统信贷类APP
                    if (gambleAppList.contains(appInfo.getAppName())) {
                        //总数
                        if (0 < days && days <= 60) {
                            last60DayGambleAppNum = last60DayGambleAppNum + 1;
                        }
                        if (days > 0 && days <= 30) {
                            last30DayGambleAppNum = last30DayGambleAppNum + 1;
                        }
                        if (days > 0 && days <= 15) {
                            last15DayGambleAppNum = last15DayGambleAppNum + 1;
                        }
                        if (days > 0 && days <= 7) {
                            last7DayGambleAppNum = last7DayGambleAppNum + 1;
                        }
                    }

                    if (StringUtils.lowerCase(appInfo.getAppName()).contains("loan")
                            || StringUtils.lowerCase(appInfo.getAppName()).contains("cash")
                            || StringUtils.lowerCase(appInfo.getAppName()).contains("money")
                            || StringUtils.lowerCase(appInfo.getAppName()).contains("coin")
                            || StringUtils.lowerCase(appInfo.getAppName()).contains("credit")
                            || StringUtils.lowerCase(appInfo.getAppName()).contains("rupee")
                            || StringUtils.lowerCase(appInfo.getAppName()).contains("kredit")

                    ) {
                        riskApps.add(appInfo.getAppName());
                        riskAppInfoList.add(appInfo);
                    }
                }
            }


            Date friskRiskAppInstallDate = null;
            for (AppInfo a : riskAppInfoList) {
                String firstInstallTime = a.getFirstInstallTime();
                if (StringUtils.isEmpty(firstInstallTime)) {
                    continue;
                }

                Date dateByStr = TimeUtils.getDateByStr(firstInstallTime, "yyyy-MM-dd");
                if (friskRiskAppInstallDate == null || dateByStr == null) {
                    friskRiskAppInstallDate = dateByStr;
                    continue;
                }

                if (dateByStr.before(friskRiskAppInstallDate)) {
                    friskRiskAppInstallDate = dateByStr;
                }
            }


            shuMeiVo.setSysAppNum(countSystem)
                    .setRiskApps(JSON.toJSONString(riskApps))
                    .setRiskAppsNum(riskApps.size())
                    .setNonSysAppNum(countNonSystem)

                    .setCreditAppNum(countCredit)
                    .setLast7DayAppNum(last7daysAppNum)
                    .setLast7DayCreditAppNum(last7daysCreditAppNum)
                    .setLast15DayAppNum(last15daysAppNum)

                    .setLast15DayCreditAppNum(last15daysCreditAppNum)
                    .setLast30DayAppNum(last30daysAppNum)
                    .setLast30DayCreditAppNum(last30daysCreditAppNum)
                    .setLast60DayAppNum(last60daysAppNum)

                    .setLast60DayCreditAppNum(last60daysCreditAppNum)
                    .setFirstRiskAppInstallDate(friskRiskAppInstallDate)
                    .setLast7DayGambleAppNum(last7DayGambleAppNum)
                    .setLast15DayGambleAppNum(last15DayGambleAppNum)

                    .setLast30DayGambleAppNum(last30DayGambleAppNum)
                    .setLast60DayGambleAppNum(last60DayGambleAppNum)
            ;

        } catch (Exception e) {
            LOGGER.error("数美数据解析出差！！！", e);
        }
    }
}
